package org.example.utlis;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.example.appstart.StartAppInfo;
import org.example.exception.ExceptionReporter;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 一个JsonUtils实例服务于一个.json文件，用path属性确定路径，用type属性确定类型。
 * @param <T>
 */
public class JsonUtils<T> {
    private String path;
    private Class<T> type;

    public JsonUtils(String path, Class<T> type) {
        this.path = path;
        this.type = type;
    }

    public List<T> readFile() {
        File file = new File(path);
        if (!file.exists()) {
            try {
                FileUtils.forceMkdirParent(new File(path));
                file.createNewFile();
            } catch (Exception e) {
                ExceptionReporter.saveLog(e, true);
            }
        }

        List<T> result = new ArrayList<>();
        try {
            String resultStr = FileUtils.readFileToString(file, Charset.defaultCharset());
            if (resultStr == null || resultStr.isEmpty()) {
                return result;
            }
            result = JSONArray.parseArray(resultStr, type);
        } catch (Exception e) {
            ExceptionReporter.saveLog(e, true);
        }
        return result;
    }

    public void writeFile(List<T> list) {
        try {
            String json = JSONObject.toJSONString(list);
            FileUtils.writeStringToFile(new File(path), json);
        } catch (Exception e) {
            ExceptionReporter.saveLog(e, true);
        }
    }
}
